<template>
  <div class="sidebar" :data="backgroundColor">
    <!--
            Tip 1: you can change the color of the sidebar's background using: data-background-color="white | black | darkblue"
            Tip 2: you can change the color of the active button using the data-active-color="primary | info | success | warning | danger"
        -->
    <!-- -->
    <div class="sidebar-wrapper" id="style-3">
      <!-- <div style="text-align:center;padding-top:15px;">
        <el-button type="success" plain><i style="margin-right: 10px;" class="el-icon-circle-plus-outline el-icon--right"></i>增加智能体</el-button>
      </div> -->
      <div class="logo" @mouseenter="toggleHover" @mouseleave="toggleHover" :class="{ 'chatItemCheck': isHovering }">
        <a aria-label="sidebar mini logo" class="simple-text logo-mini" href="http://localhost:82/#/inteAgent">
          <div class="logo-img" :class="{ 'logo-img-rtl': $rtl.isRTL }">
            <i class="el-icon-circle-plus-outline el-icon--right" style="
    color: #ffffff;
    font-size: 28px;
    margin: 2px 0px 0px 0px;
"></i>
          </div>
        </a>
        <a class="simple-text logo-normal" href="http://localhost:82/#/inteAgent">
          创建思议鸿儒
        </a>
      </div>
      <el-divider class="line"></el-divider>
      <div :class="{ chatItemCheck: activeZhiIndex === zhiIndex }" v-for="(item, zhiIndex) in title" :key="zhiIndex"
           class="logo">
        <a href="" aria-label="sidebar mini logo" class="simple-text logo-mini">
          <div class="logo-img" :class="{ 'logo-img-rtl': $rtl.isRTL }" style="background-color: white;">
            <img :src="item.src" alt="">
            <!-- <img src="../../assets/img/logo6.png" alt=""> -->
          </div>
        </a>
        <div class="simple-text logo-normal" href="" style="cursor: pointer"
             @click="setZhiActive(zhiIndex, item.id, item)">
          {{ item.name }}
          <i v-if="!item.isEditing" class="el-icon-delete el-icon--right"
             style="font-size: 20px;float: right;margin-right: 20px;margin-top: 5px;"
             @click="removeZhi(zhiIndex, item.id)"></i>
        </div>

      </div>

      <div style="text-align:center;padding-top:15px;cursor: pointer">
        <base-button type="success" @click="newChat">新建对话
        </base-button>
      </div>
      <el-input class="col-md-12 searchForChat" size="small" placeholder="搜索对话" v-model="searchInput">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <!-- <slot>

      </slot> -->
      <ul class="nav">
        <!--By default vue-router adds an active class to each route link. This way the links are colored when clicked-->
        <!-- <slot name="links">
          <sidebar-link v-for="(link, index) in sidebarLinks" :key="index" :to="link.path" :name="link.name"
            :icon="link.icon">
          </sidebar-link>
        </slot> -->
        <div class="nav-link chatItem" v-for="(item, index) in filteredChat" :key="index"
             :class="{ chatItemCheck: activeIndex === index }"
             style="cursor: pointer">
          <i v-if="!item.isEditing" class="el-icon-edit el-icon--right" @click="startEdit(index, item.id)"></i>
          <i v-if="!item.isEditing" class="el-icon-delete el-icon--right" @click="removeChat(index, item.id)"></i>
          <div v-if="!item.isEditing">
            <div class="shenlue" style="width: 185px;
    color: white;
    padding-bottom: 4px;
    margin-top: 5px;" @click="setActive(index, item.id)">{{ item.name }}
            </div>
          </div>
          <div v-else>
            <!-- <input type="text" v-model="item.name" @blur="saveEdit(index)" style="width: 136px;" /> -->
            <el-input type="text" v-model="item.name" @blur="saveEdit(index, item.name,item.id)" style="width: 200px;">
              <i slot="suffix" class="el-icon-close iconInput" @click="saveEdit(index, item.name,item.id)"
                 style="color: #75707c;line-height: 2;"></i>
              <i slot="suffix" class="el-icon-check iconinput" @click="saveEdit(index, item.name,item.id)"
                 style="color: #75707c;line-height: 2;"></i>
            </el-input>

          </div>
        </div>
      </ul>
    </div>
  </div>
</template>
<script>
// import SidebarLink from "./SidebarLink";
import axios from 'axios';
import {mapActions} from 'vuex';
import {getResourceUrl} from "../../../../config";

export default {
  props: {
    backgroundColor: {
      type: String,
      default: "blue"
    },
    activeColor: {
      type: String,
      default: "success",
      validator: value => {
        let acceptedValues = [
          "primary",
          "info",
          "success",
          "warning",
          "danger"
        ];
        return acceptedValues.indexOf(value) !== -1;
      }
    },
    sidebarLinks: {
      type: Array,
      default: () => []
    },
    autoClose: {
      type: Boolean,
      default: true
    },
  },
  provide() {
    return {
      autoClose: this.autoClose,
      addLink: this.addLink,
      removeLink: this.removeLink
    };
  },
  components: {
    // SidebarLink//这里是原本路由的位置
  },
  computed: {
    /**
     * Styles to animate the arrow near the current active sidebar link
     * @returns {{transform: string}}
     */
    arrowMovePx() {
      return this.linkHeight * this.activeLinkIndex;
    },
    shortTitle() {
      return this.title.split(' ')
        .map(word => word.charAt(0))
        .join('').toUpperCase();
    },
    filteredChat() {
      return this.chat.filter(item => {
        return item.name.toLowerCase().includes(this.searchInput.toLowerCase());
      });
    },
  },
  data() {
    return {
      inputChange: '',
      linkHeight: 65,
      activeLinkIndex: 0,
      windowWidth: 0,
      isWindows: false,
      hasAutoHeight: false,
      links: [],
      input4: '',
      chat: [
        // { name: "新建对话", isEditing: false },
        // { name: "常量和变量的区别", isEditing: false },
        // { name: "单例模式的实现与应用", isEditing: false },
        // { name: "Java访问控制修饰符应用场景", isEditing: false },
        // //Java编译中的核心角色
      ],
      title: this.$store.state.title,
      searchInput: '',
      activeIndex: 0,
      activeZhiIndex: null,
      isHovering: false,
      studentAccount: "234567",
      type: 0,
      imgType: '3',
    };
  },
  methods: {
    getResourceUrl,
    //获取聊天的id
    setChatIdInVuex(newChatId) {
      this.$store.commit('setChatId', newChatId);
    },
    //获取聊天的类型
    setType(type) {
      this.$store.commit('setChatType', type)
    },
    ...mapActions(['fetchAlerts']),
    updateTitle() {
      this.$store.commit('setTitle', this.localTitle); // 提交mutation来更新Vuex中的title
    },
    fetchChat() {
      axios.get(this.$BaseURL + '/chat/getChatRecordsList?studentAccount=' + this.studentAccount + '&type=' + this.type)
        .then(response => {
          // 确保响应状态码为200
          // 假设response.data就是你给出的JSON格式
          const {data: chatRecords} = response.data; // 解构出data数组
          // 转换数据为所需的格式，并添加isEditing: false
          this.chat = chatRecords.map(record => ({
            id: record.id,
            name: record.name || '默认名称', // 如果name为空，可以提供一个默认值
            isEditing: false,
          }));
          // 默认添加一个新建对话
          this.chat.unshift({name: '新建对话', isEditing: false});
        })
        .catch(error => {
          // 捕获请求过程中的错误
          console.error('请求出错', error);
        });
    },
    fetchChatForNew() {
      axios.get(this.$BaseURL + '/chat/getChatRecordsList?studentAccount=' + this.studentAccount + '&type=' + this.type)
        .then(response => {
          // 确保响应状态码为200
          // 假设response.data就是你给出的JSON格式
          const {data: chatRecords} = response.data; // 解构出data数组
          // 转换数据为所需的格式，并添加isEditing: false
          this.chat = chatRecords.map(record => ({
            id: record.id,
            name: record.name || '默认名称', // 如果name为空，可以提供一个默认值
            isEditing: false,
          }));
          // 默认添加一个新建对话
          // this.chat.unshift({ name: '新建对话', isEditing: false });
        })
        .catch(error => {
          // 捕获请求过程中的错误
          console.error('请求出错', error);
        });
    },
    //此处是智能体渲染
    fetchData() {
      axios.get(this.$BaseURL + '/agents/getAgents?studentAccount=234567') // 替换为您的API端点
        .then(response => {
          // 假设response.data是返回的JSON数组
          // 这里我们假设只返回一个对象，因为您提供的JSON格式看起来像是一个对象
          const data = response.data.data; // 获取数据
          console.log(data)

          const srcMap = {
            '1': '/img/robot2.0.png',
            '2': '/img/logo6.png',
            // 默认情况下使用 robot2.0.png
            default: '/img/robot2.0.png',
          };

          // 根据imageUrl设置src，并创建新的对象
          this.title = data.map(item => ({
            id: item.id, // 或者其他你需要的字段
            name: item.name,
            // 使用三元运算符或对象字面量中的计算属性来设置 src
            src: srcMap[item.imageUrl] || srcMap.default,
            recommend1: item.recommend1,
            recommend2: item.recommend2,
            recommend3: item.recommend3, // 如果API返回了这个字段
            imageUrl: item.imageUrl,
            config: item.config,
            description: item.description
            // ... 其他需要的字段
          }));

          this.fetchAlerts({
            alert1: response.data.data[0].recommend1,
            alert2: response.data.data[0].recommend2,
            alert3: response.data.data[0].recommend3
          });

        })
        .catch(error => {
          console.error(error);
          // 处理错误...
        });
    },
    toggleHover() {
      this.isHovering = !this.isHovering;
    },
    setActive(index, id) {
      // this.type=id;
      console.log(id)
      //将聊天id传递给vuex
      this.setChatIdInVuex(id)
      console.log(index)
      this.activeZhiIndex = null;
      if (this.activeZhiIndex === null) {
        // 设置当前激活的chatItem索引
        this.activeIndex = index;
      }
    },
    setZhiActive(index, id, item) {
      this.type = id
      console.log(this.type)
      this.setType(this.type)//此处是对type类型的传递
      this.fetchChat()
      this.$store.commit('setActiveChatItem', item);
      this.$store.commit('SET_NEW_CHAT_FOR_ONE', false);
      this.activeIndex = null;
      if (this.activeIndex === null) {
        this.activeZhiIndex = index;
      }
      // this.chat.unshift({ name: '新建对话', isEditing: false });
    },
    // toggleActive(index) {
    //   this.$set(this.filteredChat[index], 'isActive', !this.filteredChat[index].isActive);
    // },
    startEdit(index) {
      // console.log(this.searchInput)
      this.$set(this.chat[index], 'isEditing', true);

    },
    saveEdit(index, name, id) {
      this.$set(this.chat[index], 'isEditing', false);
      this.inputChange = name;
      console.log(this.inputChange)
      const url = this.$BaseURL + '/chat/updateChatName';

      // 如果你的 API 需要将参数放在请求体中，而不是 URL 中，你可以这样做：
      const data = {
        id: id, // 如果 API 需要这个参数在请求体中
        name: this.inputChange
      };
      // console.log(this.chat[index])
      // 发送 PUT 请求
      axios.put(url, data) // 如果参数在请求体中，则传递 data；否则，如果参数在 URL 中，则不传递
        .then(response => {
          // 请求成功后的处理
          console.log(response.data);
          // 你可以在这里更新你的 Vue 数据或其他操作
        })
        .catch(error => {
          // 请求失败后的处理
          console.error(error);
          // 你可以在这里处理错误，比如显示错误信息给用户
        });
    },
    removeChat(index, id) {
      console.log(222222)
      console.log(id)
      this.chat.splice(index, 1); // 从chat数组中移除指定索引的元素
      console.log(this.$store.state.title);
      let url = this.$BaseURL + `/chat/deleteChat?id=${id}`;

      // 使用axios发送DELETE请求
      axios.delete(url)
        .then(response => {
          // 请求成功时的处理
          console.log('Chat deleted successfully:', response.data);
          // 根据需要更新你的Vue数据或状态
        })
        .catch(error => {
          // 请求失败时的处理
          console.error('Error deleting chat:', error);
          // 可以选择向用户显示错误消息
        });
    },
    removeZhi(index, id) {
      console.log(222222)
      this.title.splice(index, 1); // 从chat数组中移除指定索引的元素
      const url = this.$BaseURL + "/agents/deleteAgent?id=" + id;
      // 发送 DELETE 请求，不使用 async/await
      axios.delete(url)
        .then(response => {
          // 处理成功的响应
          console.log('代理删除成功:', response.data);
          // 根据需要更新 UI 或执行其他操作
        })
        .catch(error => {
          // 处理请求错误
          console.error('删除代理时发生错误:', error);
          // 可以在这里给用户显示错误消息或执行其他错误处理逻辑
        });
    },
    newChat() {
      console.log(11111111)
      this.type = 0
      this.fetchChat()
      this.setType(this.type)//此处是对type类型的传递
      // this.chat.unshift({ name: '新建对话', isEditing: false });
      //for newChat
      this.$store.commit('SET_NEW_CHAT_FOR_ONE', false);
      // this.$store.commit('setChatType', this.type);//传递类型
      this.$store.commit('setAgainSearch', false); //for have new chat name
    },
    findActiveLink() {
      this.links.forEach((link, index) => {
        if (link.isActive()) {
          this.activeLinkIndex = index;
        }
      });
    },
    addLink(link) {
      const index = this.$slots.links.indexOf(link.$vnode);
      this.links.splice(index, 0, link);
    },
    removeLink(link) {
      const index = this.links.indexOf(link);
      if (index > -1) {
        this.links.splice(index, 1);
      }
    },
    //搜索逻辑
  },
  mounted() {
    this.chat.unshift({name: '新建对话', isEditing: false});
    this.fetchChat();
    this.fetchData();
    this.$watch("$route", this.findActiveLink, {
      immediate: true
    });
  },
  watch: {
    '$store.state.againSearch'(newVal) {
      if (newVal) {
        console.log(newVal)
        this.fetchChatForNew();
      }
    },  //for have new chat name
    // 如果你想在Vuex的title改变时更新localTitle，你可以添加一个watcher
    '$store.state.title': function (newVal) {
      this.localTitle = newVal;
    }
  },
};
</script>

<style scoped>
.chatItemCheck {
  border: 1.5px solid white;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.15);
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(2.5px);
  -webkit-backdrop-filter: blur(2.5px);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.18);
}

.searchForChat {
  top: 10px;
}

.searchForChat .el-input__inner {
  padding-right: 30px;
  /* 根据需要调整 */
}

.searchForChat .el-input__icon {
  position: absolute;
  left: 15px;
  /* 根据需要调整 */
  top: 50%;
  transform: translateY(-50%);
}

.chatItem {
  padding-top: 0.5rem;
  margin-top: 1rem;
  margin-left: 5px;
  margin-right: 5px;
}

.line {
  display: block;
  height: 1px;
  width: 90%;
  margin: 4px 11px;
}

.el-icon--input {
  color: black
}

.nav-link {
  padding: 0.5rem 0.5rem;
}

.sidebar .logo,
.off-canvas-sidebar .logo {
  position: relative;
  padding: 0.2rem 0.7rem;
  z-index: 4;
  margin-left: 5px;
  margin-right: 5px
}

.sidebar,
.off-canvas-sidebar {
  width: 290px;
  margin-top: 40px;
  height: calc(100vh - 55px);
}

/* 卡片ppt */
.card .card-body {
  padding: 15px;
  box-shadow: 0 9px 20px 0 rgb(156 156 158 / 37%);
  border-radius: 5px;
}

.sidebar .logo a.logo-mini .logo-img img,
.off-canvas-sidebar .logo a.logo-mini .logo-img img {
  max-width: 42px;
  /* margin-bottom: -1px; */
  margin-top: -6px;
  margin-left: -5px;
}

.sidebar .logo a.logo-mini .logo-img{
  background-color: rgba(255, 255, 255, 0);
}
.sidebar .logo[data-v-563c1b98],
.off-canvas-sidebar .logo[data-v-563c1b98] {
  position: relative;
  padding: 0.2rem 0.7rem;
  z-index: 4;
  margin-left: 5px;
  margin-right: 5px;
  margin-top: 5px;
}

.shenlue {
  width: 100px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
